const Base64 = require('./Base64.js');
require('./hmac.js');
require('./sha1.js');
const Crypto = require('./crypto.js');
var env = null
const uploadFile = function (params) {
  if (!params.filePath) {
    wx.showModal({
      title: '图片错误',
      content: '请重试',
      showCancel: false,
    })
    return;
  }
  console.log("文件路径为:" + params.filePath)
  //在手机上检测  注意
  const aliyunFileKey = params.dir + params.filePath.replace('wxfile://', '');
   
    //在开发者工具里检测  注意
  //const aliyunFileKey = params.dir + params.filePath.replace('https://', '').replace('http://tmp/',''); 

  const aliyunServerURL = 'https://hickteam.oss-cn-beijing.aliyuncs.com';

  const accessid = 'LTAI5tFwWJhpgmQ9MpeiuaZF';
  const policyBase64 = getPolicyBase64();
  const accesskey = 'SGPQtJoxyB5OZ5kTSxqYEWn9VW7jlA';
  const signature = getSignature(policyBase64, accesskey);

  // console.log('aliyunFileKey=', aliyunFileKey);
  // console.log('aliyunServerURL', aliyunServerURL);
  wx.uploadFile({
    url: aliyunServerURL, 
    filePath: params.filePath,
    name: 'file',
    formData: {
      'key': aliyunFileKey,
      'policy': policyBase64,
      'OSSAccessKeyId': accessid,
      'signature': signature,
      'success_action_status': '200',
    },
    success: function (res) {
      if (res.statusCode != 200) {
        if(params.fail){
          params.fail(res)
        }
        return;
      }
      if(params.success){
        let resData = {
          success:true,
          imageURL:aliyunServerURL+'/'+aliyunFileKey,
          msg:''
        }
        params.success(resData);
      }
    },
    fail: function (err) {
      err.wxaddinfo = aliyunServerURL;
      if (params.fail) {
        let resData = {
          success:false,
          imageURL:'',
          msg:err
        }
        params.fail(resData);
      }
      console.log(err)
    },
  })
}

const getPolicyBase64 = function () {
  let date = new Date();

  date.setHours(date.getHours() + 87600);

  let srcT = date.toISOString();

  const policyText = {
    "expiration": srcT, //设置该Policy的失效时间
    "conditions": [
      ["content-length-range", 0, 5 * 1024 * 1024] // 设置上传文件的大小限制,5mb
    ]
  };

  const policyBase64 = Base64.encode(JSON.stringify(policyText));

  return policyBase64;
}

const getSignature = function (policyBase64, accesskey) {
 
  // console.log(accesskey)

  const bytes = Crypto.HMAC(Crypto.SHA1, policyBase64, accesskey, {
    asBytes: true
  });

  const signature = Crypto.util.bytesToBase64(bytes);

  return signature;
}

module.exports = uploadFile;

